package tank.server;

import tank.server.game.MyGame;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class GameServerHandler extends SimpleChannelInboundHandler<String> {

    //全局通道组，所有客户端通道都添加进来
    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private MyGame myGame = null;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        //处理客户端操作命令
        int cmd = Integer.valueOf(s);
        myGame.handleClientCommand(ctx.channel().remoteAddress().toString(),cmd);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        myGame = MyGame.getInstance();
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + " connected.\n");
        channel.writeAndFlush("remote:" + channel.remoteAddress().toString());
        //客户端连接，就创建英雄
        myGame.currentStage.createHero(channel.remoteAddress().toString());
        //加入通道组
        channels.add(channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //广播下线消息
        myGame.currentStage.getHeros().remove(ctx.channel().remoteAddress().toString());
        System.out.println(ctx.channel().remoteAddress() +" disconnected.\n");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
